#include <QSettings>
#include <QIcon>
#include "MainModule.h"
#include "Logger.h"
#include "Codecs.h"


const QString FAILURE_TOOTLTIP("There are errors. See log for details.");


MainModule::MainModule(QWidget* parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
    QSettings ini(QCoreApplication::applicationDirPath() + "/settings.ini", QSettings::IniFormat);
    
    if (ini.allKeys().isEmpty())
        WriteDefaultIni(ini);
    
    Initialize(ini);
}

void MainModule::WriteDefaultIni(QSettings& ini)
{
    ini.setValue("DeviceName" , "uni");
    ini.setValue("MachinePath", "uni.xml");
    ini.setValue("LogDetail"  , "7");
    ini.setValue("StopTimeout", "5000");
}

void MainModule::Initialize(const QSettings& ini)
{
    logger.setDetailLevel(ini.value("LogDetail", "7").toInt());
    _deviceName = ini.value("DeviceName", "uni").toString();  
    _worker.reset(new Worker(ini.value("MachinePath", "uni.xml").toString(), ini.value("StopTimeout", "5000").toInt(), this));
}

void MainModule::Execute()
{
	logger.addn("Execution started.");

	ShowTrayIcon();
	StartWorker();
} 

void MainModule::OnSuccess()
{
    CreateTrayIcon(QIcon(":/ok"), _deviceName);
}

void MainModule::OnFailure()
{
    CreateTrayIcon(QIcon(":/failure"), FAILURE_TOOTLTIP);
}

void MainModule::CreateTrayIcon(const QIcon& icon, const QString& toolTip)
{
	if (!_trayIconMenu)
        CreateMenu();

	if (!_trayIcon)        	
        _trayIcon = QSystemTrayIconPtr(new QSystemTrayIcon);

    _trayIcon->setContextMenu(_trayIconMenu.get());
    _trayIcon->setToolTip(toolTip);
    _trayIcon->setIcon(icon);
}

void MainModule::CreateMenu()
{
	CreateMenuActions();

	_trayIconMenu = QMenuPtr(new QMenu());

    _trayIconMenu->addAction(_labelAction.get());
	_trayIconMenu->addSeparator();
    _trayIconMenu->addAction(_abortAction.get());
	_trayIconMenu->addAction(_quitAction.get());
}

void MainModule::CreateMenuActions()
{
    QString label = Decode("CP1251", _deviceName.toAscii());

    _labelAction = QActionPtr(new QAction(label, this));
    _abortAction = QActionPtr(new QAction("&Abort", this));
    _quitAction  = QActionPtr(new QAction("&Exit", this));

    connect(_quitAction.get(), SIGNAL(triggered()), SLOT(Exit()));
    connect(_abortAction.get(), SIGNAL(triggered()), SLOT(Abort()));
}

void MainModule::StartWorker()
{
    _worker->start();
}

void MainModule::StopWorker(bool gentle)
{
	_worker->Stop(gentle);
}

void MainModule::ShowTrayIcon()
{
	if (_trayIcon)
		_trayIcon->show();
}

void MainModule::HideTrayIcon()
{
	if (_trayIcon)
		_trayIcon->hide();
}

void MainModule::Abort()
{
    Quit(false);
}

void MainModule::Exit()
{
    Quit(true);
}

void MainModule::Quit(bool gentle)
{
    _worker->Stop(gentle);
    HideTrayIcon();
    logger.addn("== Uni quit ==");
    qApp->quit();
}